import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'
import { UserType } from '@/types'

// 路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginPage.vue'),
    meta: {
      title: '登录',
      requiresAuth: false,
    },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/RegisterPage.vue'),
    meta: {
      title: '注册',
      requiresAuth: false,
    },
  },
  {
    path: '/test',
    name: 'Test',
    component: () => import('@/views/TestPage.vue'),
    meta: {
      title: '测试页面',
      requiresAuth: false,
    },
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/components/Layout/MainLayout.vue'),
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/DashboardPage.vue'),
        meta: {
          title: '仪表板',
          icon: 'dashboard',
          roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
        },
      },
      // 工单管理
      {
        path: '/workorder',
        name: 'WorkOrder',
        meta: {
          title: '工单管理',
          icon: 'tool',
          roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
        },
        children: [
          {
            path: '/workorder/list',
            name: 'WorkOrderList',
            component: () => import('@/views/WorkOrder/WorkOrderListPage.vue'),
            meta: {
              title: '工单列表',
              roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
            },
          },
          {
            path: '/workorder/create',
            name: 'WorkOrderCreate',
            component: () => import('@/views/WorkOrder/WorkOrderCreatePage.vue'),
            meta: {
              title: '创建工单',
              roles: [UserType.STUDENT, UserType.ADMIN],
            },
          },
          {
            path: '/workorder/detail/:id',
            name: 'WorkOrderDetail',
            component: () => import('@/views/WorkOrder/WorkOrderDetailPage.vue'),
            meta: {
              title: '工单详情',
              roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
            },
          },
        ],
      },
      // 用户管理
      {
        path: '/user',
        name: 'User',
        meta: {
          title: '用户管理',
          icon: 'user',
          roles: [UserType.ADMIN],
        },
        children: [
          {
            path: '/user/list',
            name: 'UserList',
            component: () => import('@/views/User/UserListPage.vue'),
            meta: {
              title: '用户列表',
              roles: [UserType.ADMIN],
            },
          },
        ],
      },
      // 维修类别管理
      {
        path: '/category',
        name: 'Category',
        meta: {
          title: '维修类别',
          icon: 'tags',
          roles: [UserType.ADMIN],
        },
        children: [
          {
            path: '/category/list',
            name: 'CategoryList',
            component: () => import('@/views/Category/CategoryListPage.vue'),
            meta: {
              title: '类别管理',
              roles: [UserType.ADMIN],
            },
          },
        ],
      },
      // 物料管理
      {
        path: '/material',
        name: 'Material',
        meta: {
          title: '物料管理',
          icon: 'box-plot',
          roles: [UserType.REPAIR_WORKER, UserType.ADMIN],
        },
        children: [
          {
            path: '/material/list',
            name: 'MaterialList',
            component: () => import('@/views/Material/MaterialListPage.vue'),
            meta: {
              title: '物料列表',
              roles: [UserType.REPAIR_WORKER, UserType.ADMIN],
            },
          },
        ],
      },
      // 技能管理
      {
        path: '/skill/manage',
        name: 'SkillManage',
        component: () => import('@/views/Skill/SkillManagePage.vue'),
        meta: {
          title: '技能分配',
          icon: 'team',
          roles: [UserType.ADMIN],
        },
      },
      {
        path: '/skill/overview',
        name: 'SkillOverview',
        component: () => import('@/views/Skill/SkillOverviewPage.vue'),
        meta: {
          title: '技能总览',
          icon: 'team',
          roles: [UserType.ADMIN],
        },
      },
      // 通知中心
      {
        path: '/notification',
        name: 'Notification',
        component: () => import('@/views/Notification/NotificationListPage.vue'),
        meta: {
          title: '通知中心',
          icon: 'bell',
          roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
        },
      },
      // 个人中心
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/ProfilePage.vue'),
        meta: {
          title: '个人中心',
          icon: 'user',
          roles: [UserType.STUDENT, UserType.REPAIR_WORKER, UserType.ADMIN],
        },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFoundPage.vue'),
    meta: { title: '页面不存在' },
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 宿舍维修报修平台` : '宿舍维修报修平台'

  // 如果访问的是登录或注册页面
  if (to.path === '/login' || to.path === '/register') {
    // 如果已登录（从持久化存储中恢复），重定向到首页
    if (userStore.isLoggedIn) {
      next('/dashboard')
      return
    }
    next()
    return
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth !== false) {
    // 如果有持久化的用户信息，但需要验证session是否仍然有效
    if (userStore.userInfo) {
      try {
        // 验证当前session是否有效
        const success = await userStore.fetchUserInfo()
        if (!success) {
          // session已过期，清除持久化数据并跳转到登录页
          userStore.userInfo = null
          next('/login')
          return
        }
      } catch (error: unknown) {
        console.error('验证用户session失败:', error)
        // session验证失败，清除持久化数据并跳转到登录页
        userStore.userInfo = null
        next('/login')
        return
      }
    } else {
      // 没有用户信息，直接跳转到登录页
      next('/login')
      return
    }

    // 检查角色权限
    if (to.meta.roles && Array.isArray(to.meta.roles)) {
      if (!userStore.hasRole(to.meta.roles as UserType[])) {
        message.error('没有权限访问该页面')
        next('/dashboard')
        return
      }
    }
  }

  next()
})

export default router
